package cn.stylefeng.guns.modular.gridsystem.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.annotion.BusinessLog;
import cn.stylefeng.guns.core.enums.LogAnnotionOpTypeEnum;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.core.util.PoiUtil;
import cn.stylefeng.guns.modular.gridsystem.entity.*;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizDeviceStatusAssessParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizExceptionLogParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.BizDeviceExceptionRecordResult;
import cn.stylefeng.guns.modular.gridsystem.model.result.BizExceptionResult;
import cn.stylefeng.guns.modular.gridsystem.model.result.DeviceStatusAssessInfoResult;
import cn.stylefeng.guns.modular.gridsystem.service.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.*;

/**
 * 设备状态评估 控制器
 *
 * @author: ssy
 * @date: 2022/08/03 09:17
 */
@RestController
@Slf4j
public class BizDeviceStatusAssessController {

    @Resource
    private BizDeviceStatusAssessService bizDeviceStatusAssessService;

    @Resource
    private BizDeviceStatusAssessInfoService bizDeviceStatusAssessInfoService;

    @Resource
    private BizExceptionLogService bizExceptionLogService;

    @Resource
    private BizExceptionService bizExceptionService;

    @Resource
    private BizUploadScoreService bizUploadScoreService;

    @Resource
    private BizDeviceService bizDeviceService;

    /**
     * 分页查询设备状态评估
     *
     * @author ssy
     * @date 2022/02/16 10:59
     */
    @GetMapping("/bizDeviceStatusAssess/page")
    @BusinessLog(title = "设备状态评估_分页查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(BizDeviceStatusAssessParam bizDeviceStatusAssessParam) {
        return new SuccessResponseData(bizDeviceStatusAssessService.page(bizDeviceStatusAssessParam));
    }

    /**
     * 获取全部设备状态评估
     *
     * @author ssy
     * @date 2022/02/16 10:59
     */
    @GetMapping("/bizDeviceStatusAssess/list")
    @BusinessLog(title = "设备状态评估_查询所有", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(BizDeviceStatusAssessParam bizDeviceStatusAssessParam) {
        return new SuccessResponseData(bizDeviceStatusAssessService.list(bizDeviceStatusAssessParam));
    }

    /**
     * 查看详情设备状态评估
     *
     * @author ssy
     * @date 2022/02/16 10:59
     */
    @GetMapping("/bizDeviceStatusAssess/detail")
    @BusinessLog(title = "设备状态评估_查看详情", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(BizDeviceStatusAssessParam bizDeviceStatusAssessParam) {
        return new SuccessResponseData(bizDeviceStatusAssessService.detail(bizDeviceStatusAssessParam));
    }


    /**
     * 删除设备状态评估
     *
     * @author ssy
     * @date 2022/02/16 10:59
     */
    @PostMapping("/bizDeviceStatusAssess/delete")
    @BusinessLog(title = "设备状态评估_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody BizDeviceStatusAssessParam bizDeviceStatusAssessParam) {
        bizDeviceStatusAssessService.delete(bizDeviceStatusAssessParam);

        return new SuccessResponseData();
    }

    @PostMapping("/bizDeviceStatusAssess/export")
    @BusinessLog(title = "设备状态评估_导出", opType = LogAnnotionOpTypeEnum.EXPORT)
    public ResponseData export(@RequestBody BizDeviceStatusAssessParam bizDeviceStatusAssessParam) {
        bizDeviceStatusAssessService.export(bizDeviceStatusAssessParam);
        return new SuccessResponseData();
    }

    @PostMapping("/bizDeviceStatusAssess/exportCustom")
    @BusinessLog(title = "设备状态评估_自定义导出", opType = LogAnnotionOpTypeEnum.EXPORT)
    public void exportCustom(Integer stationId,Integer deviceId,String startTime,String endTime) {
        List<BizDeviceExceptionRecordResult> recordResults = bizDeviceService.getDeviceException(stationId,startTime,endTime);

        List<DeviceStatusAssessInfoResult> assessInfoList = new ArrayList<>();
        for (BizDeviceExceptionRecordResult result:recordResults){
            BizDeviceStatusAssessParam param = new BizDeviceStatusAssessParam();
            param.setDeviceId(result.getDeviceId());
            param.setErrorNumber(result.getUnprocessedRecords());
            param.setNormalNumber(result.getProcessedRecords());
            param.setAssessTime(DateUtil.date());
            param.setType(3);

            if(ObjectUtil.isEmpty(deviceId)){
                List<BizExceptionResult> results = bizExceptionService.getDeviceExceptionList(stationId,0,startTime,endTime);
                Set<Integer> exceptIds = new HashSet<>();
                for (BizExceptionResult exceptionResult : results){
                    Integer exceptionId = exceptionResult.getExceptionId();
                    exceptIds.add(exceptionId);
                }
                int[] array = exceptIds.stream().mapToInt(Integer::intValue).toArray();
                assessInfoList = bizDeviceStatusAssessInfoService.getAssessInfoList(array);
                PoiUtil.exportExcelWithStream("设备状态评估报告.xls", DeviceStatusAssessInfoResult.class, assessInfoList);
                return;
            }else {
                if(deviceId.equals(result.getDeviceId())){
                    List<BizExceptionResult> results = bizExceptionService.getDeviceExceptionList(stationId,deviceId,startTime,endTime);
                    Set<Integer> exceptIds = new HashSet<>();
                    for (BizExceptionResult exceptionResult : results){
                        Integer exceptionId = exceptionResult.getExceptionId();
                        exceptIds.add(exceptionId);
                    }
                    int[] array = exceptIds.stream().mapToInt(Integer::intValue).toArray();
                    assessInfoList = bizDeviceStatusAssessInfoService.getAssessInfoList(array);
                    PoiUtil.exportExcelWithStream("设备状态评估报告.xls", DeviceStatusAssessInfoResult.class, assessInfoList);
                    return;
                }
            }
        }
        PoiUtil.exportExcelWithStream("设备状态评估报告.xls", DeviceStatusAssessInfoResult.class, assessInfoList);
    }



    @PostMapping("/v2/api/assess")
    public ResponseData assess() {
        //查询日志表总的上传数量：正常+故障
        QueryWrapper<BizUploadScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("count(1) as allAcount","device_id as deviceId");
        queryWrapper.groupBy("device_id");
        List<Map<String, Object>> list = bizUploadScoreService.listMaps(queryWrapper);
        final BizDeviceStatusAssessParam bizDeviceStatusAssessParam = new BizDeviceStatusAssessParam();
        for (Map<String, Object> map : list){
            Integer deviceId = Integer.parseInt(map.get("deviceId").toString());
            //查询设备对应故障
            final QueryWrapper<BizException> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("device_id",deviceId);
            final List<BizException> exceptionList = bizExceptionService.list(queryWrapper1);
            int count = 0;
            final List<Integer> exceptionIds = new ArrayList<>();
            for (BizException bizException:exceptionList){
                final Integer exceptionId = bizException.getId();
                //记录子主表故障关联id
                exceptionIds.add(exceptionId);
                //查询故障数量
                final QueryWrapper<BizExceptionLog> wrapper = new QueryWrapper<>();
                wrapper.eq("exception_id",exceptionId);
                count += bizExceptionLogService.count(wrapper);
            }
            //总数量
            final int allAcount = Integer.parseInt(map.get("allAcount").toString());
            bizDeviceStatusAssessParam.setNormalNumber(allAcount - count);
            bizDeviceStatusAssessParam.setErrorNumber(count);
            bizDeviceStatusAssessParam.setDeviceId(deviceId);
            bizDeviceStatusAssessParam.setAssessTime(DateUtil.date());
            //添加故障评估主表
            final Integer assessId = bizDeviceStatusAssessService.add(bizDeviceStatusAssessParam);
            log.info("添加结果assessId为：{}",assessId);
            //添加故障评估字表
            final BizDeviceStatusAssessInfo bizDeviceStatusAssessInfo = new BizDeviceStatusAssessInfo();
            bizDeviceStatusAssessInfo.setAssessId(assessId);
            bizDeviceStatusAssessInfo.setExceptionIds(StringUtils.join(exceptionIds.toArray(),","));
            bizDeviceStatusAssessInfoService.save(bizDeviceStatusAssessInfo);
        }
        return new SuccessResponseData();
    }

}
